from flask import Flask, render_template, request
import sqlite3 as sql

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/enternew')
def newstudent():
    return render_template('student2.html')

@app.route('/addrec', methods=['POST', 'GET'])
def addrec():
    if request.method == 'POST':
        try:
            nm = request.form['nm']
            addr = request.form['add']
            city = request.form['city']
            pin = request.form['pin']
            with sql.connect('students') as con:
                cur = con.cursor()
                cur.execute(f"INSERT INTO students (name,address,city,pin) VALUES ('{nm}','{addr}','{city}','{pin}')")
                con.commit()
                msg = "Record added mothefucka"
        except(RuntimeError):
            con.rollback
            msg = "Error mothefucka"+RuntimeError
        finally:
            con.close()
            return render_template("result2.html", msg = msg)

@app.route("/list")
def list():
    con = sql.connect('students')
    con.row_factory = sql.Row
    cur = con.cursor()
    cur.execute("SELECT * FROM students")
    rows = cur.fetchall()
    return render_template("list.html", rows = rows)

if __name__ == '__main__':
    app.run(debug=True)
        
